<template>
    <el-autocomplete
      v-model="nv[fvData.fdName]"
      :value-key="expression.sourceFdName"
      :fetch-suggestions="querySearch"
      clearable
      class="inline-input w-50"
      placeholder="Please Input"
      @select="handleSelect"
    />
</template>

<script>
import { onMounted, ref, computed, getCurrentInstance } from 'vue'
import { ElMessage } from 'element-plus'
export default {
  name: 'AutoComplete',
  props: {
    fvData: {
      default: null,
      type: Object
    }
  },
  setup (props) {
    const nv = computed(() => {
      return props.fvData.getNv();
    });
    const expression = ref({});
    const currentInstance = getCurrentInstance();
    const querySearch = (queryString, cb) => {
      const nvLayout = getParentNvLayout();
      const dataSource = nvLayout.getDataSource(expression.value.sourceName);
      const sourceNv = dataSource.getNv();
      if (sourceNv == null) {
        const empty = [];
        cb(empty);
        return;
      }
      let childNdName = expression.value.childNdName;
      if (childNdName === ".") childNdName = props.fvData.ndName;
      if (!queryString) {
        const result = sourceNv[childNdName];
        cb(result);
        return;
      }
      const sourceChildNvs = sourceNv[childNdName];
      const result = sourceChildNvs.filter((item) => {
        return item[expression.value.sourceFdName].indexOf(queryString) >= 0
      })
      cb(result)
    }

    function getParentNvLayout() {
      let parent = currentInstance.parent;
      while (parent != null) {
        if (parent.type.name === "NvLayout") { break; }
        parent = parent.parent;
      }
      return parent.proxy;
    }

    onMounted(() => {
      const str = props.fvData.fdLayout.expression;
      if (!str) {
        ElMessage({
          type: 'error',
          message: '没有配置自动改填充组件表达式'
        });
        return;
      }
      expression.value = JSON.parse(str);
    });

    return {
      nv,
      querySearch,
      expression
    }
  }
}
</script>
